#define _CRT_SECURE_NO_WARNINGS 1

#include"LinkList.h"

void InitList(ListNode** phead)
{
	assert(phead);
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if(newnode == NULL)
	{
		perror("Init:");
	}
	*phead = newnode;
	(*phead)->next = NULL;
	(*phead)->value = 0;
}

bool ListInsert(ListNode* phead, int i, ElemType value)
{
	assert(phead);
	if (i < 1)
	{
		return false;
	}
	if (phead->next == NULL && i == 1)
	{
		ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
		if (newnode == NULL)
		{
			perror("Insert malloc:");
			return false;
		}
		newnode->value = value;
		newnode->next = NULL;
		phead->next = newnode;
		return true;
	}
	int j = 0;
	ListNode* cur = phead;
	while (j < i - 1 && cur != NULL)
	{
		j++;
		cur = cur->next;
	}
	if (cur == NULL)
	{
		return false;
	}
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("Insert malloc:");
		return false;
	}
	newnode->value = value;
	newnode->next = cur->next;
	cur->next = newnode;
	return true;
}

void DispList(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != NULL)
	{
		printf("%c ", cur->value);
		cur = cur->next;
	}
	printf("\n");
}

int ListLength(ListNode* phead)
{
	assert(phead);
	int i = 0;
	ListNode* cur = phead->next;
	while (cur != NULL)
	{
		i++;
		cur = cur->next;
	}
	return i;
}

bool ListEmpty(ListNode* phead)
{
	assert(phead);
	return phead->next == NULL;
}

bool GetElem(ListNode* phead, int i, ElemType* value)
{
	assert(phead);
	if (i < 1)
	{
		return false;
	}
	int j = 0;
	ListNode* cur = phead->next;
	while (j != i - 1 && cur != NULL)
	{
		j++;
		cur = cur->next;
	}
	if (j == i - 1 && cur != NULL)
	{
		*value = cur->value;
		return true;
	}
	else
	{
		return false;
	}
}

int LocateElem(ListNode* phead, ElemType value)
{
	assert(phead);
	ListNode* cur = phead->next;
	int i = 0;
	while (cur != NULL)
	{
		i++;
		if (cur->value == value)
		{
			return i;
		}
		cur = cur->next;
	}
	return 0;
}

bool ListDelete(ListNode* phead, int i)
{
	assert(phead);
	if (i < 1)
	{
		return false;
	}
	int j = 0;
	ListNode* prev = phead;
	ListNode* cur = phead->next;
	while (j != i - 1 && cur != NULL)
	{
		j++;
		prev = prev->next;
		cur = cur->next;
	}
	if (j == i - 1 && cur != NULL)
	{
		prev->next = cur->next;
		free(cur);
		cur = NULL;
		return true;
	}
	else
	{
		return false;
	}
}

void DestroyList(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead;
	while (phead != NULL)
	{
		phead = phead->next;
		free(cur);
		cur = phead;
	}
}